package Extend;

import java.util.Random;
import java.util.Scanner;

/*
    生成的验证码为：BkhD
    abcd
    生成的验证码为：n1wX
    aaaa
    生成的验证码为：Fm1a
    fm1a
    验证通过
 */
public class Ex03 {
    public static void main(String[] args) {
        //1 题给需求
        while(true){
            String password = newCode();
            System.out.println("系统生成的验证码为(忽略大小写)：" + password);

            Scanner sc = new Scanner(System.in);
            if (checkScan(sc,password))break;
        }
        System.out.println("验证通过...");

        /*2  +自动循环直到输入正确
        String password = newCode();
        System.out.println("系统生成的验证码为：" + password);

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入验证码");
        while(!checkScan(sc, password)){
            System.out.println("请输入验证码");
        }
        System.out.println("输入正确");
         */
    }

    public static String newCode(){
        //生成字符库
        StringBuilder s1 = new StringBuilder();
        for (char i = 'A',j = 'a'; i <= 'Z' && j <= 'z'; i++,j++) {
            s1.append(i);
            s1.append(j);
        }
        for (char i = '0'; i <= '9'; i++) {
            s1.append(i);
        }
        //System.out.println(s1.toString());检查字符库用
        //生成随机验证码
        Random rd = new Random();
        StringBuilder s2 = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            s2.append(s1.charAt(rd.nextInt(62)));
        }
        return s2.toString();

    }
    public static boolean checkScan(Scanner sc,String s){
        if (s.equalsIgnoreCase(sc.next())){//忽略大小写
            return true;
        }else {
            return false;
        }
    }
}
